<?php

namespace mpend\models;

use Yii;
use yii\base\Model;
use mpend\models\User;
use common\exceptions\ModelHttpException;

/**
 * 找回密码
 * ForgetForm 
 */
class ResetPasswordForm extends Model {

    public $mobile;
    public $code;
    public $password;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['mobile', 'code', 'password'], 'required'],
            ['mobile', 'string', 'min' => 11, 'max' => 11],
            ['code', 'string', 'min' => 4, 'max' => 4],
            ['password', 'string', 'min' => 6],
            ['mobile', '\common\validators\MobileValidator'],
//            ['password', 'validatePassword'],
            ['code', 'validateCaptchaCode'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute) {
        if (!$this->hasErrors()) {
            //@todo
            //密码强度校验
        }
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateCaptchaCode($attribute) {
        if (!$this->hasErrors()) {
            $captcha = Yii::$app->cache->get('captcha_' . SmsCaptchaForm::SCOPE_FORGET . '_' . $this->mobile);
            if ($captcha == false) {
                $this->addError($attribute, '验证码已过期');
            } elseif ($captcha !== $this->$attribute) {
                $this->addError($attribute, '验证码不正确');
            }
        }
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function resetPassword() {
        if (!$this->validate()) {
            throw new ModelHttpException('注册失败', $this->getFirstErrors());
        }

        $user = new User();
        $user->username = 'M' . $this->mobile;
        $user->mobile = $this->mobile;
        $user->setPassword($this->password);
        $user->generateAuthKey();

        if (!$user->save()) {
            throw new ModelHttpException('注册失败', $user->getFirstErrors());
        }

        return $user;
    }

}
